/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : home.js                                 
*  Description  : 클럽개별메인 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-20  이윤노    Created.  
*  2012-06-00  이윤노    Complete.  
*******************************************************************************/

jQuery(function($){
	
	//승인요청회원목록
	function clsClubOutMember(){
		this._HTMLDom = null;
		this.listData = null;
		this.page = null;
		this.profileData= null;
		this._init();		
	}
	
	clsClubOutMember.prototype = {
		_init: function(){
			var $layer  = $("div#container section#main_content article.board_list");
			this._HTMLDom = {
				"$layer": $layer	
				, "$element": $layer.find("table.clublist_w tbody tr.loop_odd:first")
				, "$empty": $("article.board_list_none").html("등록된 글이 없습니다.").hide()
			}
			this.profileData = [];
			$layer.find("table.clublist_w tbody").empty();	
		}	
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData, page){			
			this.listData = thisData;
			this.page = page;
			this.display();
		}
		, addProfile: function(idx, oneData){
			this.profileData[idx] = oneData;
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"].find("table.clublist_w tbody");
			var $element = this._HTMLDom["$element"]
			var thisClass = this;
			
			$layer.empty();
			
			if(!this.listData.length) {
				this._HTMLDom["$empty"].show();
				$("div#idClubOutMemberListPage").hide();
				$("p.btn_area").hide();
			}
			
			for(var i=0;i<this.listData.length;++i){
				$layer.append($element.clone(true));	
			}
			
			var num = this.getPagePerNum(); 
			
			$layer.find("tr").each(function(n){				
				$(this).find("td:eq(1)").html(num--);
				$(this).find("td:eq(2) span.nickname").html(thisClass.listData[n]["사용자정보"]["닉네임"]).hover(function(event){
					_gf.showProfileLayer($(this), thisClass.profileData[n], "left", 0, $(this).height());
				}, function(event){
					_gf.closeProfileLayer();
				});
				$(this).find("td:eq(2) img").attr("src", _gf.filePath2Url(thisClass.listData[n]["사용자정보"]["이미지"]));
				$(this).find("td:eq(3)").html(thisClass.listData[n]["가입질문답변"]);
				$(this).find("td:eq(4)").html(getFormatDateYmd(thisClass.listData[n]["가입신청일"],"-"));
			});
		}
		, spinStart: function(){
			this._HTMLDom["$layer"].spin();
		}
		, spinEnd: function(){
			this._HTMLDom["$layer"].spin(false);
		}
		, isNodata: function(){
			
		}
		, $getCheckedData: function(){
			var $checkbox = this._HTMLDom["$layer"].find("table.clublist_w tbody input:checkbox");
			var userId=null;
			
			if($checkbox.filter(":checked").length > 0){
				userId = "";
			}
			
			for(var i=0;i<$checkbox.filter(":checked").length;++i){
				if(userId) userId += ",";
				var idx = $checkbox.index($checkbox.filter(":checked").eq(i));
				userId += this.listData[idx]["사용자정보"]["아이디"];
			}			
			return userId;	
		}
		, hide: function(){
			this._HTMLDom["$layer"].hide();	
			$("p.btn_area").hide();
			$("div#idClubOutMemberListPage").hide();
			$("article.club_q").hide();
			$("article.club_box_info").show();
		}
		, show: function(){
			this._HTMLDom["$layer"].show();	
			$("p.btn_area").show();
			$("div#idClubOutMemberListPage").show();
			$("article.club_q").show();			
			$("article.club_box_info").hide();
		}
		, getPagePerNum: function(){
			var $page = this.page;
			return $page.getTotalCount() - ($page.getCountPerPage()*($page.getPage()-1));
		}
	}
	
	function clsComm()
	{
		this.clubOutMemberList = null;
		this.clubOutMemberListPageData = null;
		this.clubOutMemberListRequest = null;		
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){			
			this.clubOutMemberListRequest = {
				"동호회키": null
				, "페이지": null
				, "검색어": null
				, "검색종류": null
				, "정렬키":null
				, "정렬방향":null
			}
			
			this.clubOutMemberListPageData = {
				"전체수": null	
			}
		}	
//------------------------ 탈퇴회원목록조회------------------------//		
		, getClubOutMemberList: function(){			
			var thisClass = this;
			
			var szPage = this.clubOutMemberListRequest["페이지"];
			var szClubSeq = this.clubOutMemberListRequest["동호회키"];
			var szSearchType = this.clubOutMemberListRequest["검색종류"];
			var szSearchOption = this.clubOutMemberListRequest["검색어"];
			var szSortType = this.clubOutMemberListRequest["정렬종류"];
			var szSortOption = this.clubOutMemberListRequest["정렬방향"];
			
			// ajax 시작			
			//parameter setting and run
			_gf.ajax({
				"sid":"CL001",
				"servicename":"getMemberList",
				"listcount":10,
				"currpageno":szPage
			}, {
				  "clubSeq": szClubSeq
				  , "memberStatus": 1
			}, function(ret){
				
				// callback and mapping
				thisClass.clubOutMemberList = [];
			
				if(ret["msp"]["contents"]["items"]){
					
					thisClass.clubOutMemberListPageData = {
						"전체수": ret["msp"]["contents"]["@totalcount"]
					}
					
					if(!ret["msp"]["contents"]["items"].length){
						ret["msp"]["contents"]["items"] = new Array(ret["msp"]["contents"]["items"]);
					}
					
					for(var i=0;i<ret["msp"]["contents"]["items"].length;i++){
						var arr = [];
						var obj = ret["msp"]["contents"]["items"][i];
						
						//동호회목록
						thisClass.clubOutMemberList.push({
							"동호회키": _util.nvl(obj["clubSeq"])
							, "사용자정보": {
								"아이디": _util.nvl(obj["clubMemberUserInfo"]["userId"])
								, "닉네임": _util.nvl(obj["clubMemberUserInfo"]["nickname"])
								, "이미지": _util.nvl(obj["clubMemberUserInfo"]["path"]) + _util.nvl(obj["clubMemberUserInfo"]["saveFileName"])
							}
							, "회원구분": _util.nvl(obj["memberRoleName"])
							, "게시글수": _util.nvl(obj["myBoardCnt"])
							, "댓글수": _util.nvl(obj["myReplyCnt"])
							, "방문수": _util.nvl(obj["visitCount"])
							, "가입일": _util.nvl(obj["joinDate"])
							, "최종방문일": _util.nvl(obj["memberRoleName"])
							, "정보공개":{
								"휴대폰": "전체공개"
								, "이메일": "전체공개"
								, "추가정보": "전체공개"
							}
							, "가입질문답변": _util.nvl(obj["joinment"])
							, "가입신청일": _util.nvl(obj["requestDate"])
						});
						
					}         
				}
				
				$(thisClass).trigger("evtFinishClubOutMemberList");
			});						
		}
		, getClubOutMemberListData: function(){
			return this.clubOutMemberList;
		}
		, getClubOutMemberListPageData: function(){
			return this.clubOutMemberListPageData;	
		}
		, setClubOutMemberListRequest: function(key, val){
			this.clubOutMemberListRequest[key] = val;	
		}
//------------------------ 탈퇴회원목록조회------------------------//		
//------------------------ 승인허락------------------------//	
		, UpdateMemeberAssign: function(arg){			
			var thisClass = this;
			var szClubSeq = arg["동호회키"];
			var szUserId = arg["아이디"];
			
			// ajax 시작			
			//parameter setting and run
			_gf.ajax({
				"sid":"CL001",
				"servicename": "acceptMember"
			}, {
				"clubSeq": szClubSeq
				, "userId": szUserId
				, "memberStatus": 0
				
			}, function(ret){				
				
				// callback and mapping
				var resData = {
					"응답코드": (ret["msp"]["contents"]["serviceResult"] == "00000"?true:false)
					, "메세지":_gf.getResultMsg(ret, ["승인"])
				}
				
				$(thisClass).trigger("evtFinishUpdateMemeberAssign", [resData]);
				
			});
			// ajax 끝
		}
//------------------------ 승인허락------------------------//		
//------------------------ 승인거절------------------------//
		, UpdateMemeberReject: function(arg){			
			var thisClass = this;
			var szClubSeq = arg["동호회키"];
			var szUserId = arg["아이디"];
			
			// ajax 시작			
			//parameter setting and run
			_gf.ajax({
				"sid":"CL001",
				"servicename": "acceptMember"
			}, {
				"clubSeq": szClubSeq
				, "userId": szUserId
				, "memberStatus": 7
				
			}, function(ret){				
				
				// callback and mapping
				var resData = {
					"응답코드": (ret["msp"]["contents"]["serviceResult"] == "00000"?true:false)
					, "메세지": _gf.getResultMsg(ret, ["거절"])			
				}
				
				$(thisClass).trigger("evtFinishUpdateMemeberReject", [resData]);
				
			});
			// ajax 끝
		}
//------------------------ 승인거절------------------------//
	}
	
	function clsControl()
	{
		this.objComm = null;
		
		this.objClubInfo = null
		this.objRole = null;
		
		this.objClubOutMember = null;
		
		this.objSearchType = null;
		this.objSearchText = null;
		this.objSearchSort = null;
				
		this.club_seq = null;
		this.club_my = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			var member_id = document.objUtil.getCookie("member_id");
			this.club_seq = document.objUtil.getParam("club_seq");
			this.club_my = (document.objUtil.getParam("club_my") == "Y") ? 1:0;
			
			if(!this.club_seq) document.location.href = "../club/club.html";
			
			if(!member_id) {
				if(confirm("로그인 후 이용하여 주세요.")){
					_gf.goLogin();						
				}else{
					document.location.href = "../club/club.html";
				}				
			}else if(!this.club_seq) {
				document.location.href = "../club/club.html";
			}
			
			this.objComm = new clsComm();
			this.objClubOutMember = new clsClubOutMember();
			this.objClubOutMemberPage = new _gf.makePaging($("#idClubOutMemberListPage"), 10, 10);
						
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			$.ajax({
				url: "js/self_club_top.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return (_clubControl.getClubInfo().infoData);
			}, function(){				
				_gf.spinEnd();;
				thisClass._start();
			});	
		}
		, _role: function(){
			if(!this.objRole.isMember()){
				alert(this.objRole.getError());
				document.location.href="home.html?club_seq="+this.infoData["동호회키"];
			}else if(!this.objRole.isAdmin()){
				alert(this.objRole.getError());
				document.location.href="home.html?club_seq="+this.infoData["동호회키"];
			}
		}
		, _start: function(){		
			this.objClubInfo = _clubControl.getClubInfo();
			this.objRole = new clsRole(this.objClubInfo.infoData);
			this._role();
			
			if(this.objClubInfo.infoData["가입유형"]=="Y"){
				this.objClubOutMember.show();
			}else {
				this.objClubOutMember.hide();
				return;
			}
			
			//탈퇴자목록 조회
			this.objClubOutMember.spinStart();
			this.objComm.setClubOutMemberListRequest("동호회키", this.club_seq);
			this.objComm.setClubOutMemberListRequest("페이지", 1);
			this.objClubOutMemberPage.setPage(1);
			this.objComm.getClubOutMemberList();
		}
		, _bind: function(){
			var thisClass = this;
			
			// 탈퇴자목록 조회 완료이벤트
			$(this.objComm).bind("evtFinishClubOutMemberList", function(){
				var thisData = thisClass.objComm.getClubOutMemberListData();
				var pageData = 	thisClass.objComm.getClubOutMemberListPageData();
				
				for(var i=0;i<thisData.length;++i){
					
					_gf.getMemberInfo({
						"아이디": thisData[i]["사용자정보"]["아이디"]
						, "인덱스": i
						, "콜백": function(res, info, arg){
							
							thisClass.objClubOutMember.addProfile(arg["인덱스"], info);
						}
					});
				}
				
				// 페이지 부에 전체 수설정 				
				thisClass.objClubOutMemberPage.setTotalCount(pageData["전체수"]);
				thisClass.objClubOutMemberPage.display();
				
				thisClass.objClubOutMember.setList(thisData, thisClass.objClubOutMemberPage);				
				thisClass.objClubOutMember.spinEnd();
			});
			
			// 페이지이동 이벤트
			$(this.objClubOutMemberPage).bind("evtPageClick", function(){
				var thisPage = this.getPage();
				
				thisClass.objComm.setClubOutMemberListRequest("페이지", thisPage);
				thisClass.objClubOutMember.spinStart();
				thisClass.objComm.getClubOutMemberList();
			});
			
			// 승인허락 완료이벤트
			$(this.objComm).bind("evtFinishUpdateMemeberAssign", function(event, resData){
				_gf.spinEnd();		
				alert(resData["메세지"]);				
				if(resData["응답코드"]){				
					thisClass.objClubOutMember.spinStart();
					thisClass.objComm.getClubOutMemberList();
				}	
			});
			
			// 승인거절 완료이벤트
			$(this.objComm).bind("evtFinishUpdateMemeberReject", function(event, resData){
				_gf.spinEnd();		
				alert(resData["메세지"]);			
				if(resData["응답코드"]){				
					thisClass.objClubOutMember.spinStart();
					thisClass.objComm.getClubOutMemberList();
				}	
			});
			
			//가입승인 버튼 이벤트
			$("p.btn_area a img[alt=가입승인]").click(function(event){
				event.preventDefault();				
				var userId = thisClass.objClubOutMember.$getCheckedData();
				if(!userId) {
					alert("회원을 선택해주세요.");
					return;
				}
				var submitData = {
					"동호회키": thisClass.club_seq
					, "아이디": userId	
				}
				_gf.spinStart();					
				thisClass.objComm.UpdateMemeberAssign(submitData);
			});
			
			//가입거절 버튼 이벤트
			$("p.btn_area img[alt=가입거절]").click(function(event){
				event.preventDefault();				
				var userId = thisClass.objClubOutMember.$getCheckedData();
				if(!userId) {
					alert("회원을 선택해주세요.");
					return;
				}
				var submitData = {
					"동호회키": thisClass.club_seq
					, "아이디": userId	
				}
				_gf.spinStart();					
				thisClass.objComm.UpdateMemeberReject(submitData);
			});
			
			// 체크박스
			this.objClubOutMember.$getLayer().on("click", "input:checkbox", function(){
				var n = thisClass.objClubOutMember.$getLayer().find("input:checkbox").index($(this));
				var c = $(this).prop("checked");
				
				if(n == 0){
					thisClass.objClubOutMember.$getLayer().find("input:checkbox").prop("checked", c);
				}else{
					c = !(thisClass.objClubOutMember.$getLayer().find("input:checkbox:gt(0):not(:checked)").length);
					
					thisClass.objClubOutMember.$getLayer().find("input:checkbox:eq(0)").prop("checked", c);
				}
			});
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();	
});	